package com.tbit.uqbike.object.pojo.dto;

import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.webmanager.util.ExportExcelUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.apache.commons.collections.CollectionUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yee_
 * @version 1.0
 * @date 2023/1/11 14:24
 */
@Getter
@Setter
@ToString
@Accessors(chain = true)
public class GiftCardBatchUpdateDTO {
    /**
     * 手机号excel文件
     */
    @NotNull(message = "请上传excel文件")
    private MultipartFile file;
    /**
     * 区域id
     */
    @NotNull(message = "请选择区域")
    private Integer accountId;
    /**
     * 变动金额
     */
    @NotNull(message = "请填写变动金额")
    private Integer money;
    /**
     * 操作密钥
     */
    private String operaPsw;
    @NotNull(message = "请填写备注")
    @Length(max = 32, message = "备注过长")
    private String remark;

    private Set<String> userPhones;

    private LoginInfo loginInfo;

    public void valid() {
        if (this.money == 0) {
            throw new BaseException("变动金额不能为0");
        }
        analyzeExcel();
    }

    private void analyzeExcel() {
        try {
            List<List<String>> entityResult = ExportExcelUtils.readExcelDataFirst(this.file.getBytes(), 0);
            if (CollectionUtils.isEmpty(entityResult)) {
                throw new BaseException("excel为空请填写信息后重试。");
            }
            int maxValue = 5000;
            if (entityResult.size() > maxValue) {
                throw new BaseException("单次批量修改上限为5000人,请调整后重新上传");
            }
            userPhones = entityResult.stream().flatMap(Collection::stream).filter(StringUtils::hasText).collect(Collectors.toSet());
        } catch (IOException e) {
            throw new BaseException("excel文件解析异常。");
        }
    }

}
